package com.sharainy.contoller;

import com.alibaba.fastjson.JSONObject;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.sharainy.pojo.Merchant;
import com.sharainy.pojo.Recharge;
import com.sharainy.service.MerchantService;
import com.sharainy.service.RechargeService;
import com.sharainy.util.*;
import org.jdom.JDOMException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.time.Instant;
import java.util.*;

@Controller
@RequestMapping("/recharge")
public class RechargeController {

    @Autowired
    private RechargeService rechargeService;
    @Autowired
    private MerchantService merchantService;

    @RequestMapping(value = "/rechargePage")
    public String index(){
        return "recharge";
    }
    @RequestMapping("/rechargeDetail")
    @ResponseBody
    public RestResponse rechargeDetail(int merchantId){
        JSONObject jsonMain = new JSONObject();
        Recharge recharge = rechargeService.selectRecharge(merchantId);
        Merchant merchant = merchantService.selectMerchantById(merchantId+"");
        if (recharge!=null){
            recharge.setAfterrecharge(merchant.getBalance());
            jsonMain.put("recharge",recharge);
        }else{
            Recharge recharge1 = new Recharge();
            recharge1.setMerchantid(merchantId);
            recharge1.setAfterrecharge(merchant.getBalance());
            jsonMain.put("recharge",recharge1);
        }

        RestResponse restResponse = RestResponse.succuess();
        restResponse.setData(jsonMain);
        return restResponse;

    }
    @RequestMapping("/recharge")
    @ResponseBody
    public RestResponse rechargeDetail(Recharge recharge){
        JSONObject jsonMain = new JSONObject();

        try {
            Merchant merchant = merchantService.selectMerchantById(recharge.getMerchantid()+"");
            recharge.setBeforerecharge(merchant.getBalance());
            recharge.setAfterrecharge(recharge.getBeforerecharge()+recharge.getRechargeamount());
            recharge.setRecordtime(Instant.now().getEpochSecond());
            int rechargeId = rechargeService.addRecharge(recharge);
            Map<String, String> map = new HashMap<String, String>();
            map.put("id",merchant.getId()+"");
            map.put("balance",recharge.getAfterrecharge()+"");
            merchantService.modifyBalance(map);
            recharge.setId(rechargeId);
            String companyName = merchantService.selectCompanyName(merchant.getCompanyid());
            RestResponse restResponse = RestResponse.succuess();
            jsonMain.put("companyName",companyName);
            jsonMain.put("recharge",recharge);
            jsonMain.put("merchant",merchant);
            restResponse.setData(jsonMain);
            return restResponse;
        }catch (Exception e){
            RestResponse restResponse = RestResponse.fail();
            return restResponse;
        }
    }

    /**
     * 微信支付生成二维码
     * @param request
     * @param response
     * @param modelMap
     */
    @ResponseBody
    @RequestMapping("/qrcode")
    public void qrcode(HttpServletRequest request, HttpServletResponse response,
                       ModelMap modelMap) {
        try {
            String merchantId = request.getParameter("merchantId");
            String recharge = request.getParameter("rechargeamount");
            String timestamp = request.getParameter("timestamp");
            String text = rechargeService.weixinPay(recharge, merchantId, timestamp);
            System.out.println("User:"+text);
            int width = 300;
            int height = 300;
            //二维码的图片格式
            String format = "gif";
            Hashtable hints = new Hashtable();
            //内容所使用编码
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            BitMatrix bitMatrix;
            try {
                bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);
                QRUtil.writeToStream(bitMatrix, format, response.getOutputStream());
            } catch (WriterException e) {
                e.printStackTrace();
            }

        } catch (Exception e) {
        }
    }

    /**
     *
     * @Description: 前往支付宝第三方网关进行支付
     * @author dbb
     */
    @RequestMapping(value = "/goAlipay", produces = "text/html; charset=UTF-8")
    @ResponseBody
    public String goAlipay(String rechargeamount, String merchantId, String timestamp) throws Exception {


        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
        //商户订单号，商户网站订单系统中唯一订单号，必填
        String outtradeno =merchantId+"-"+timestamp.substring(0,10);
        //付款金额，必填
        String totalamount = rechargeamount;
        //订单名称，必填
        String subject = merchantId;
        //商品描述，可空
        String body = "预付费账户充值" ;

        // 该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。 该参数数值不接受小数点， 如 1.5h，可转换为 90m。
        String timeoutexpress = "1c";

        alipayRequest.setBizContent("{\"outtradeno\":\""+ outtradeno +"\","
                + "\"totalamount\":\""+ totalamount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"timeoutexpress\":\""+ timeoutexpress +"\","
                + "\"productcode\":\"FASTINSTANTTRADEPAY\"}");

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        return result;
    }
    /**
     *
     * @Title: AlipayController.java
     * @Package com.sihai.controller
     * @Description: 支付宝同步通知页面
     * Copyright: Copyright (c) 2017
     * Company:FURUIBOKE.SCIENCE.AND.TECHNOLOGY
     *
     * @author sihai
     * @date 2017年8月23日 下午8:51:01
     * @version V1.0
     */
    @RequestMapping(value = "/alipayReturnNotice")
    public String alipayReturnNotice(HttpServletRequest request, HttpServletRequest response) throws Exception {

        System.out.println("支付成功, 进入同步通知接口...");

        //获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名

       // ModelAndView mv = new ModelAndView("alipaySuccess");
        //——请在这里编写您的程序（以下代码仅作参考）——
        if(signVerified) {
            //商户订单号
            String outtradeno = new String(request.getParameter("outtradeno").getBytes("ISO-8859-1"),"UTF-8");

            //支付宝交易号
            String tradeno = new String(request.getParameter("tradeno").getBytes("ISO-8859-1"),"UTF-8");

            //付款金额
            String totalamount = new String(request.getParameter("totalamount").getBytes("ISO-8859-1"),"UTF-8");

            // 修改叮当状态，改为 支付成功，已付款; 同时新增支付流水
       //     orderService.updateOrderStatus(outtradeno, tradeno, totalamount);


           // Orders order = orderService.getOrderById(outtradeno);
          //  Product product = productService.getProductById(order.getProductId());

            System.out.println("********************** 支付成功(支付宝同步通知) **********************");
            System.out.println("* 订单号: {}"+ outtradeno);
            System.out.println("* 支付宝交易号: {}"+ tradeno);
            System.out.println("* 实付金额: {}"+ totalamount);
            System.out.println("***************************************************************");
            String[] orders = outtradeno.split("-");
            Merchant merchant = merchantService.selectMerchantById(orders[0]);
            Recharge addRecharge = new Recharge();
            addRecharge.setMerchantid(merchant.getId());
            addRecharge.setRecordtime(Long.parseLong(orders[1]));
            addRecharge.setBeforerecharge(merchant.getBalance());
            addRecharge.setRechargeamount(Float.parseFloat(totalamount));
            addRecharge.setAfterrecharge(addRecharge.getBeforerecharge()+addRecharge.getRechargeamount());
            addRecharge.setChannel(3);
            addRecharge.setMerchantname(merchant.getName());
            rechargeService.addRecharge(addRecharge);
            Map<String, String> map = new HashMap<String, String>();
            map.put("id",merchant.getId()+"");
            map.put("balance",addRecharge.getAfterrecharge()+"");
            merchantService.modifyBalance(map);

        }else {
            System.out.println("支付, 验签失败...");
        }
        return "redirect:/views/close.html ";

    }
    @ResponseBody
    @RequestMapping("/hadPay")
    public RestResponse hadPay(String orderStr){
        JSONObject jsonMain = new JSONObject();
        String[] orders = orderStr.split("-");
        Map<String, String> map = new HashMap<String, String>();
        map.put("merchantId",orders[0]);
        map.put("recordtime",orders[1].substring(0,10));
        Recharge recharge = rechargeService.selectRechargeByTimeAndId(map);
        if (recharge!=null){
            Merchant merchant = merchantService.selectMerchantById(recharge.getMerchantid()+"");
            String companyName = merchantService.selectCompanyName(merchant.getCompanyid());
            RestResponse restResponse = RestResponse.succuess();
            jsonMain.put("companyName",companyName);
            jsonMain.put("recharge",recharge);
            jsonMain.put("merchant",merchant);
            restResponse.setData(jsonMain);
            return restResponse;
        }else{
            RestResponse restResponse = RestResponse.fail();
            return restResponse;
        }

    }

    /**
     * 微信平台发起的回调方法，
     * 调用我们这个系统的这个方法接口，将扫描支付的处理结果告知我们系统
     * @throws JDOMException
     * @throws Exception
     */
    @RequestMapping("/weChatPay")
    public void weixinNotify(HttpServletRequest request, HttpServletResponse response) throws JDOMException, Exception {
        System.out.println("============================================================");
       //读取参数
        InputStream inputStream ;
        StringBuffer sb = new StringBuffer();
        inputStream = request.getInputStream();
        String s ;
        BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        while ((s = in.readLine()) != null){
            sb.append(s);
        }
        in.close();
        inputStream.close();

        //解析xml成map
        Map<String, String> m = new HashMap<String, String>();
        m = XMLUtil4.doXMLParse(sb.toString());

        //过滤空 设置 TreeMap
        SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
        Iterator it = m.keySet().iterator();
        while (it.hasNext()) {
            String parameter = (String) it.next();
            String parameterValue = m.get(parameter);

            String v = "";
            if(null != parameterValue) {
                v = parameterValue.trim();
            }
            packageParams.put(parameter, v);
        }
        // 账号信息
        String key = PayConfigUtil.API_KEY; //key
        //判断签名是否正确
        if(PayToolUtil.isTenpaySign("UTF-8", packageParams,key)) {
            //------------------------------
            //处理业务开始
            //------------------------------
            String resXml = "";
            if("SUCCESS".equals((String)packageParams.get("resultcode"))){
                // 这里是支付成功
                //////////执行自己的业务逻辑////////////////
                String mchid = (String)packageParams.get("mchid");
                String openid = (String)packageParams.get("openid");
                String issubscribe = (String)packageParams.get("issubscribe");
                String outtradeno = (String)packageParams.get("outtradeno");
                String totalfee = (String)packageParams.get("totalfee");
                String body = (String)packageParams.get("body");
                //////////执行自己的业务逻辑////////////////
                //暂时使用最简单的业务逻辑来处理：只是将业务处理结果保存到session中
                //（根据自己的实际业务逻辑来调整，很多时候，我们会操作业务表，将返回成功的状态保留下来）
                String[] orders = outtradeno.split("-");
                Merchant merchant = merchantService.selectMerchantById(orders[0]);
                Recharge addRecharge = new Recharge();
                addRecharge.setMerchantid(merchant.getId());
                addRecharge.setRecordtime(Long.parseLong(orders[1]));
                addRecharge.setBeforerecharge(merchant.getBalance());
                addRecharge.setRechargeamount(Float.parseFloat(totalfee)/100);
                addRecharge.setAfterrecharge(addRecharge.getBeforerecharge()+addRecharge.getRechargeamount());
                addRecharge.setChannel(2);
                addRecharge.setMerchantname(merchant.getName());
                rechargeService.addRecharge(addRecharge);
                Map<String, String> map = new HashMap<String, String>();
                map.put("id",merchant.getId()+"");
                map.put("balance",addRecharge.getAfterrecharge()+"");
                merchantService.modifyBalance(map);

                //通知微信.异步确认成功.必写.不然会一直通知后台.八次之后就认为交易失败了.
                resXml = "<xml>" + "<returncode><![CDATA[SUCCESS]]></returncode>"
                        + "<returnmsg><![CDATA[OK]]></returnmsg>" + "</xml> ";

            } else {
                resXml = "<xml>" + "<returncode><![CDATA[FAIL]]></returncode>"
                        + "<returnmsg><![CDATA[报文为空]]></returnmsg>" + "</xml> ";
            }
            //------------------------------
            //处理业务完毕
            //------------------------------
            BufferedOutputStream out = new BufferedOutputStream(
                    response.getOutputStream());
            out.write(resXml.getBytes());
            out.flush();
            out.close();
        } else{
            System.out.println("通知签名验证失败");
        }
    }

}
